package com.kd.d5000acquire.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;

@Slf4j
@ChannelHandler.Sharable
public class ServerClientHandler extends SimpleChannelInboundHandler<ByteBuf> {



    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        System.out.println("red");
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx)  {
//        while (true){
//            String message = (String) queue.poll();
//            if(message == null){
//                continue;
//            }
//            log.info("准备发送消息,消息内容为:"+ message.toString());
//            ChannelFuture channelFuture = ctx.channel().writeAndFlush(Unpooled.copiedBuffer(message, CharsetUtil.UTF_8));
//            try {
//                channelFuture.sync();
//            } catch (Exception e){
//                log.error("TCP发送消息失败,准备消息重新发送",e);
//                queue.offer(message);
//            }
//            log.info("消息发送成功");
//        }
    }

    // 数据读取完毕的处理
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.err.println("客户端读取数据完毕");
    }

    // 出现异常的处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.err.println("client 读取数据出现异常");
        ctx.close();
    }


}
